package utils

import (
	"fmt"
	"time"

	"github.com/avast/retry-go"
	"github.com/zeromicro/x/errors"
)

type RetryFunc func() error

type retryServer struct {
	RetryFunc
	Attempts uint
	Delay    time.Duration
}

// 异常重试
func (r retryServer) TryExecuteFunc() error {
	if r.Attempts == 0 {
		r.Attempts = 3
	}

	if r.Delay == 0 {
		r.Delay = time.Second * 1
	}
	if r.RetryFunc == nil {
		return errors.New(4000, "请传入重试函数")
	}
	err := retry.Do(
		retry.RetryableFunc(r.RetryFunc),
		retry.Attempts(r.Attempts),
		retry.Delay(r.Delay),
	)
	if err != nil {
		fmt.Printf("重试失败")
	}
	return nil
}

func newRetryServer() *retryServer {
	return &retryServer{}
}
